/*******************************************************************************
 * Package: com.hngtrust.iir.report.service.impl
 * Type:    reportRightServiceImpl
 * Date:    2021/9/14 13:58
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.report.service.impl;

import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.elk.exception.ElkErrorType;
import com.hngtrust.iir.elk.exception.ElkException;
import com.hngtrust.iir.report.controller.dto.ReportRightUpadteVO;
import com.hngtrust.iir.report.dto.ReportRightUserOrDepartDTO;
import com.hngtrust.iir.report.controller.dto.ReportRightUserOrDepartVO;
import com.hngtrust.iir.report.controller.dto.ReportRightVO;
import com.hngtrust.iir.report.dto.ReportRightDTO;
import com.hngtrust.iir.report.controller.dto.ReportRightQueryVO;
import com.hngtrust.iir.report.entity.ReportLog;
import com.hngtrust.iir.report.entity.ReportRight;
import com.hngtrust.iir.report.service.PrivateReportService;
import com.hngtrust.iir.report.service.ReportLogService;
import com.hngtrust.iir.report.service.ReportRightBacService;
import com.hngtrust.iir.report.service.ReportRightService;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.util.ElkUtils;
import com.tiger.util.MyHttpClient;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 内部研报-研报权限表
 *
 * @author Yujiaqi
 * @date 2021/9/14 13:58
 */
@Service
@Slf4j
public class ReportRightBacServiceImpl implements ReportRightBacService {
    
    
    //文件路径
    @Value("${elk.search.url}")
    private String elkUrl;
    
    @Value(("${elk.search.indexname.private-report}"))
    private String fileName;
    
    @Autowired
    private MyIdGenerator myIdGenerator;
    @Autowired
    private ReportRightService reportRightService;
    @Autowired
    private ReportLogService reportLogService;
    @Autowired
    private PrivateReportService privateReportService;
    
    /**
     * 内部研报-新增收藏列表
     */
    @Override
    public void addRight(ReportRightVO reportRightVO) {
        List<ReportRight> reportRightList = new ArrayList<>();
        List<Long> userId = reportRightVO.getUserId();
        if (userId != null && userId.size() > 0){
            for (Long aLong : userId) {
                ReportRight reportRight = new ReportRight();
                reportRight.setId(myIdGenerator.nextId());
                reportRight.setCreateTime(new Date());
                User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
                reportRight.setCreateUserId(loginUser.getId());
                reportRight.setReportId(reportRightVO.getReportId());
                reportRight.setUserId(aLong);
                reportRightList.add(reportRight);
            }
        }
        if(reportRightList != null && reportRightList.size() >0) {
            reportRightService.add(reportRightList);
        }
    }
    
    /**
     * 内部研报-研报权限表列表
     * @param reportRightQueryVO
     * @return
     */
    @Override
    public List<ReportRightDTO> listRight(ReportRightQueryVO reportRightQueryVO) {
        ReportRight reportRight = new ReportRight();
        reportRight.setReportId(reportRightQueryVO.getReportId());
        List<ReportRightDTO> list = reportRightService.queryReportRights(reportRight);
        return list;
    }
    
    /**
     * 内部研报-修改研报权限表
     * @param reportRightUpadteVO
     */
    @Override
    public void updateRight(ReportRightUpadteVO reportRightUpadteVO) {
        Long reportId = reportRightUpadteVO.getReportId();
        //先根据研报id删除数据
        reportRightService.deleteRightByReportId(reportId);
        List<ReportRight> reportRights = new ArrayList<>();
        List<Long> userId = reportRightUpadteVO.getUserId();
        //新增所有数据
        if (userId != null && userId.size() > 0) {
            for (Long aLong : userId) {
                ReportRight reportRight = new ReportRight();
                reportRight.setId(myIdGenerator.nextId());
                reportRight.setReportId(reportRightUpadteVO.getReportId());
                reportRight.setUserId(aLong);
                reportRight.setCreateTime(new Date());
                User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
                reportRight.setCreateUserId(loginUser.getId());
                reportRights.add(reportRight);
            }
            reportRightService.addRightByReportId(reportRights);
        }
        //修改主表权限标识字段，和下载权限设置字段
        reportRightService.updatePirvateReport(reportRightUpadteVO.getRightTag(),reportRightUpadteVO.getDwonTag(),reportRightUpadteVO.getReportId());
        
        //在内部研报操作日志表新建一条记录
        ReportLog reportLog = new ReportLog();
        reportLog.setId(myIdGenerator.nextId());
        //根据研报ID获取研报名称
        String reportTitle = privateReportService.queryReportTitleById(reportRightUpadteVO.getReportId());
        reportLog.setReportId(reportRightUpadteVO.getReportId());
        reportLog.setTitle(reportTitle);
        reportLog.setOptType("修改权限");
        reportLog.setCreateTime(new Date());
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        reportLog.setCreateUserId(loginUser.getId());
        reportLogService.add(reportLog);
        
        String url;
        if (StringUtil.isBlank(elkUrl) || StringUtil.isBlank(fileName)) {
            throw new ElkException(ElkErrorType.ELK_URL_INDEX_BLANK, elkUrl, fileName);
        }
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            url = elkUrl + fileName + "/_update_by_query";
        } else {
            url = elkUrl + "/" + fileName + "/_update_by_query";
        }
        ReportRight right = new ReportRight();
        right.setReportId(reportRightUpadteVO.getReportId());
        List<Long> collect = reportRightService.queryList(right).stream().map(r -> r.getUserId())
                .collect(Collectors.toList());
        MyHttpClient client = new MyHttpClient();
        JSONConfig config = new JSONConfig();
        config.setOrder(true);
        JSONObject params = new JSONObject(config);
        JSONObject source = new JSONObject();
        source.put("source","ctx._source.iir['iir_tag_id'] = '"+collect+"';ctx._source.iir['iir_right_tag'] ='"+reportRightUpadteVO.getRightTag()+"';ctx._source.iir['iir_dow_tag'] ='"+reportRightUpadteVO.getDwonTag()+"'");
        JSONObject m = new JSONObject();
        JSONObject f= new JSONObject();
        f.put("iir.iir_mysql_id",reportRightUpadteVO.getReportId());
        m.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
        params.put("script",source);
        params.put("query",m);
        
        log.info("修改参数{}",params.toString());
        client.postJson(url,params);
    }
    
    /**
     * 内部研报-权限部门或人员搜索
     * @param reportRightUserOrDepartVO
     */
    @Override
    public List<ReportRightUserOrDepartDTO> queryUserOrDepartment(ReportRightUserOrDepartVO reportRightUserOrDepartVO) {
        List<ReportRightUserOrDepartDTO> reportRightUserOrDepartDTO = new ArrayList<>();
        if(StringUtils.isNotBlank(reportRightUserOrDepartVO.getName())) {
            reportRightUserOrDepartDTO = reportRightService.queryUserOrDepartment(reportRightUserOrDepartVO.getName());
        }
        if (reportRightUserOrDepartDTO != null && reportRightUserOrDepartDTO.size() >0){
            for (ReportRightUserOrDepartDTO rightUserOrDepartDTO : reportRightUserOrDepartDTO) {
                if(rightUserOrDepartDTO.getType() == 2){
                    //根据部门id查询下边是否有部门
                    List<Long> longs = new ArrayList<>();
                    List<Long> list = reportRightService.queryIdByParentId(rightUserOrDepartDTO.getDepartmentId());
                    if (list != null && list.size() > 0){
                        //部门下的用户
                        List<Long> list1 = reportRightService.queryUserIdByDeptId(rightUserOrDepartDTO.getDepartmentId());
                        if(list1 != null && list1.size() >0) {
                            longs.addAll(list1);
                        }
                        List<Long> recursion = recursion(list, longs);
                        Set<Long> set = new HashSet<>(recursion);
                        String join = StringUtils.join(set, ",");
                        rightUserOrDepartDTO.setUserId(join);
                    }else {
                        //最底层部门了，到用户表查询下边的用户
                        List<Long> list1 = reportRightService.queryUserIdByDeptId(rightUserOrDepartDTO.getDepartmentId());
                        if(list1 != null && list1.size() >0) {
                            String join = StringUtils.join(list1, ",");
                            rightUserOrDepartDTO.setUserId(join);
                        }else {
                            rightUserOrDepartDTO.setUserId(String.valueOf(rightUserOrDepartDTO.getDepartmentId()));
                        }
                    }
                }
            }
        }
        return reportRightUserOrDepartDTO;
    }
    
    private List<Long> recursion(List<Long> list,List<Long> longs){
        if (list != null && list.size() > 0){
            for (Long aLong : list) {
                longs.add(aLong);
                //查询部门下的部门
                List<Long> longList = reportRightService.queryIdByParentId(aLong);
                if (longList != null && longList.size() > 0){
                    //查询部门下的人员
                    List<Long> list2 = reportRightService.queryUserIdByDeptId(aLong);
                    if (list2 != null && list2.size() > 0){
                        longs.addAll(list2);
                    }
                    recursion(longList,longs);
                }else {
                    List<Long> list1 = reportRightService.queryUserIdByDeptId(aLong);
                    if(list1 != null && list1.size() > 0) {
                        for (Long aLong1 : list1) {
                            longs.add(aLong1);
                        }
                    }else {
                        longs.add(aLong);
                    }
                }
            }
        }
        return longs;
    }
}




